<template>
  <view class="product-detail">
    <!-- 产品轮播图 -->
    <view class="product-swiper">
      <swiper class="swiper" indicator-dots="true" autoplay="false" circular="true">
        <swiper-item v-for="(image, index) in productImages" :key="index">
          <image :src="image" class="swiper-image" mode="aspectFill"></image>
        </swiper-item>
      </swiper>
    </view>

    <!-- 产品基本信息 -->
    <view class="product-info">
      <view class="price-section">
        <text class="current-price">¥{{ selectedSku ? selectedSku.price : product.price }}</text>
        <text class="original-price" v-if="selectedSku && selectedSku.original_price > selectedSku.price">¥{{ selectedSku.original_price }}</text>
      </view>
      <text class="product-name">{{ product.name }}</text>
      <view class="product-meta">
        <text class="stock-info">库存: {{ selectedSku ? selectedSku.stock : 0 }}{{ selectedSku ? selectedSku.unit : '' }}</text>
        <text class="sales-info">已售: {{ product.sales || 0 }}</text>
      </view>
    </view>

    <!-- 规格选择 -->
    <view class="spec-section" @click="showSkuPopup">
      <view class="spec-header">
        <text class="spec-title">选择规格</text>
        <view class="spec-selected">
          <text class="selected-text" v-if="selectedSku">{{ getSpecText(selectedSku.spec_combination) }}</text>
          <text class="selected-text placeholder" v-else>请选择规格</text>
          <image src="/static/image/icon_arrow_right.png" class="arrow-icon" mode="aspectFit"></image>
        </view>
      </view>
      <!-- 无货提示 -->
      <view class="stock-warning" v-if="isOutOfStock && selectedSku">
        <text class="warning-text">暂无库存</text>
      </view>
    </view>

    <!-- 产品详情 -->
    <view class="detail-section">
      <view class="section-title">
        <text class="title-text">商品详情</text>
      </view>
      <view class="detail-content">
        <rich-text :nodes="product.description"></rich-text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
<!--      <view class="cart-btn" @click="goToCart">-->
<!--        <image src="/static/image_副本/icon_lists.png" class="cart-icon" mode="aspectFit"></image>-->
<!--        <text class="cart-text">购物车</text>-->
<!--        <view class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</view>-->
<!--      </view>-->
      <view class="action-btns">
<!--        <button class="add-cart-btn" :class="{ 'disabled': isOutOfStock }" @click="showSkuPopup">-->
<!--          {{ isOutOfStock ? '无货' : '加入购物车' }}-->
<!--        </button>-->
        <ZButton type="secondary" class="buy-btn" :disabled="isOutOfStock" @click="showSkuPopup" :text="isOutOfStockText">
        </ZButton>
      </view>
    </view>

    <!-- SKU选择弹窗 -->
    <u-popup v-model="showSkuSelector" mode="bottom" border-radius="32rpx 32rpx 0 0" height="80%">
      <view class="sku-popup">
        <view class="popup-header">
          <view class="product-preview">
            <image :src="selectedSku ? selectedSku.image : product.cover" class="preview-image" mode="aspectFill"></image>
            <view class="preview-info">
              <text class="preview-price">¥{{ selectedSku ? selectedSku.price : product.price }}</text>
              <text class="preview-stock">库存: {{ selectedSku ? selectedSku.stock : 0 }}{{ selectedSku ? selectedSku.unit : '' }}</text>
            </view>
          </view>
          <text class="popup-close" @click="closeSkuPopup">×</text>
        </view>

        <view class="popup-content">
          <!-- 规格选择 -->
          <scroll-view class="sku-section-list" scroll-y="true">
            <view class="sku-section" v-for="(spec, specKey) in specOptions" :key="specKey">
              <text class="spec-name">{{ specKey }}</text>
              <view class="spec-options">
                <view
                  class="spec-option"
                  v-for="option in spec"
                  :key="option"
                  :class="{ active: selectedSpecs[specKey] === option }"
                  @click="selectSpec(specKey, option)"
                >
                  <text class="option-text">{{ option }}</text>
                </view>
              </view>
            </view>
          </scroll-view>

          <!-- 数量选择 -->
          <view class="quantity-section">
            <text class="quantity-label">购买数量</text>
            <view class="quantity-control">
              <text class="quantity-btn" @click="decreaseQuantity">-</text>
              <input class="quantity-input" v-model="quantity" type="number" />
              <text class="quantity-btn" @click="increaseQuantity">+</text>
            </view>
          </view>
        </view>

        <view class="popup-footer">
<!--          <button class="add-cart-action-btn" :class="{ 'disabled': isOutOfStock }" @click="addToCart">-->
<!--            {{ isOutOfStock ? '无货' : '加入购物车' }}-->
<!--          </button>-->
          <ZButton class="buy-action-btn" :disabled="isOutOfStock" @click="buyNow" :text="isOutOfStockText">
          </ZButton>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import Navbar from "../../components/Navbar.vue";
import api from "../../config/api.js";
import ZButton from "../../components/ZButton.vue";

export default {
  components: {ZButton, Navbar },
  data() {
    return {
      productId: null,
      product: {
        id: null,
        name: '',
        cover: '',
        images: [],
        description: '',
        price: 0,
        sales: 0
      },
      skuList: [],
      specList: [], // 规格列表
      selectedSku: null,
      selectedSpecs: {},
      quantity: 1,
      showSkuSelector: false,
      cartCount: 0,
      actionType: 'add_cart', // 'add_cart' 或 'buy_now'
      loading: false
    }
  },
  computed: {
    // 产品图片列表
    productImages() {
      if (this.product.images && this.product.images.length > 0) {
        try {
          return JSON.parse(this.product.images);
        } catch (e) {
          return [this.product.cover];
        }
      }
      return [this.product.cover];
    },

    // 规格选项
    specOptions() {
      const options = {};

      // 从规格列表中生成选项
      this.specList.forEach(spec => {
        if (spec.spec_values) {
          try {
            const specValues = JSON.parse(spec.spec_values);
            options[spec.spec_name] = specValues;
          } catch (e) {
            console.error('解析规格值失败:', e);
          }
        }
      });

      // 如果没有规格列表，从SKU中提取
      if (Object.keys(options).length === 0) {
        this.skuList.forEach(sku => {
          if (sku.spec_combination) {
            try {
              const specs = JSON.parse(sku.spec_combination);
              Object.keys(specs).forEach(key => {
                if (!options[key]) {
                  options[key] = [];
                }
                if (!options[key].includes(specs[key])) {
                  options[key].push(specs[key]);
                }
              });
            } catch (e) {
              console.error('解析规格失败:', e);
            }
          }
        });
      }

      return options;
    },

    // 当前选择的SKU是否有效
    isSkuValid() {
      return this.selectedSku && this.selectedSku.stock > 0;
    },

    // 是否无货状态
    isOutOfStock() {
      return (!this.selectedSku || this.selectedSku.stock <= 0) ? true : false;
    },
    isOutOfStockText() {
      console.log(this.isOutOfStock, 'isOutOfStock');
      return this.isOutOfStock ? '无货' : '立即购买';
    }
  },
  onLoad(options) {
    this.productId = options.id || 1;
    this.loadProductDetail();
    this.loadCartCount();
  },
  methods: {
    // 加载产品详情
    async loadProductDetail() {
      if (this.loading) return;

      this.loading = true;
      try {
        uni.showLoading({
          title: '加载中...'
        });

        const result = await api.getProduct(this.productId);
        this.product = result;

        // 如果产品详情中包含 skus 和 specs，直接使用
        if (result.skus && result.skus.length > 0) {
          this.skuList = result.skus;
        }

        if (result.specs && result.specs.length > 0) {
          this.specList = result.specs;
        }

        // 如果没有包含关联数据，单独获取
        if (!result.skus || result.skus.length === 0) {
          await this.loadSkuList();
        }

        if (!result.specs || result.specs.length === 0) {
          await this.loadSpecList();
        }

        // 默认选择第一个有库存的SKU
        this.selectDefaultSku();

      } catch (error) {
        console.error('加载产品详情失败:', error);
        uni.showToast({
          title: '商品不存在',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        },1000)
      } finally {
        this.loading = false;
        uni.hideLoading();
      }
    },

    // 加载SKU列表
    async loadSkuList() {
      try {
        const params = {
          product_id: this.productId,
          status: 1 // 只获取启用的SKU
        };
        const result = await api.getProductSkuList(params);
        this.skuList = result;
      } catch (error) {
        console.error('加载SKU列表失败:', error);
      }
    },

    // 加载规格列表
    async loadSpecList() {
      try {
        const params = {
          product_id: this.productId,
          status: 1 // 只获取启用的规格
        };
        const result = await api.getProductSpecList(params);
        this.specList = result;
      } catch (error) {
        console.error('加载规格列表失败:', error);
      }
    },

    // 选择默认SKU
    selectDefaultSku() {
      if (this.skuList.length > 0) {
        // 默认选择第一个有库存的SKU
        const availableSku = this.skuList.find(sku => sku.stock > 0);
        if (availableSku) {
          this.selectSkuBySpecs(availableSku);
        } else {
          // 如果没有有库存的SKU，选择第一个
          this.selectSkuBySpecs(this.skuList[0]);
        }
      }
    },

    // 加载购物车数量
    loadCartCount() {
      const cartItems = uni.getStorageSync('cartItems') || [];
      // 获取用户信息
      const userInfo = uni.getStorageSync('userInfo') || {};

      // 如果用户已登录，只统计当前用户的购物车商品
      if (userInfo && userInfo.id) {
        this.cartCount = cartItems.filter(item => item.user_id === userInfo.id).length;
      } else {
        this.cartCount = cartItems.length;
      }
    },

    // 显示SKU选择弹窗
    showSkuPopup() {
      this.showSkuSelector = true;
    },

    // 关闭SKU选择弹窗
    closeSkuPopup() {
      this.showSkuSelector = false;
    },

    // 选择规格
    selectSpec(specKey, option) {
      this.$set(this.selectedSpecs, specKey, option);
      this.updateSelectedSku();
    },

    // 根据规格选择SKU
    updateSelectedSku() {
      const selectedSku = this.skuList.find(sku => {
        if (!sku.spec_combination) return false;
        try {
          const specs = JSON.parse(sku.spec_combination);
          return Object.keys(this.selectedSpecs).every(key =>
            specs[key] === this.selectedSpecs[key]
          );
        } catch (e) {
          return false;
        }
      });

      this.selectedSku = selectedSku;

      // 如果选择的SKU库存不足，调整数量
      if (selectedSku && this.quantity > selectedSku.stock) {
        this.quantity = selectedSku.stock;
      }

      // 如果未找到对应SKU，显示提示
      if (!selectedSku && Object.keys(this.selectedSpecs).length > 0) {
        uni.showToast({
          title: '暂无库存',
          icon: 'none'
        });
      }
    },

    // 根据SKU设置规格选择
    selectSkuBySpecs(sku) {
      if (sku.spec_combination) {
        try {
          const specs = JSON.parse(sku.spec_combination);
          this.selectedSpecs = { ...specs };
          this.selectedSku = sku;
        } catch (e) {
          console.error('解析SKU规格失败:', e);
        }
      }
    },

    // 增加数量
    increaseQuantity() {
      if (this.selectedSku && this.quantity < this.selectedSku.stock) {
        this.quantity++;
      }
    },

    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },

    // 获取规格文本
    getSpecText(specCombination) {
      if (!specCombination) return '';
      try {
        const specs = JSON.parse(specCombination);
        return Object.values(specs).join('、');
      } catch (e) {
        return '';
      }
    },

    // 加入购物车
    addToCart() {
      if (this.isOutOfStock) {
        uni.showToast({
          title: '暂无库存',
          icon: 'none'
        });
        return;
      }

      if (!this.isSkuValid) {
        uni.showToast({
          title: '请选择有效规格',
          icon: 'none'
        });
        return;
      }

      // 获取用户信息
      const userInfo = uni.getStorageSync('userInfo') || {};

      const cartItem = {
        id: this.selectedSku.id,
        product_id: this.product.id,
        product_name: this.product.name,
        product_cover: this.product.cover,
        sku_code: this.selectedSku.sku_code,
        spec_combination: this.selectedSku.spec_combination,
        price: this.selectedSku.price,
        quantity: this.quantity,
        unit: this.selectedSku.unit,
        user_id: userInfo.id || null
      };

      // 获取现有购物车
      let cartItems = uni.getStorageSync('cartItems') || [];

      // 如果用户已登录，只操作当前用户的购物车商品
      if (userInfo && userInfo.id) {
        const userCartItems = cartItems.filter(item => item.user_id === userInfo.id);
        const otherUserItems = cartItems.filter(item => item.user_id !== userInfo.id);

        // 检查是否已存在相同SKU
        const existingIndex = userCartItems.findIndex(item => item.id === cartItem.id);
        if (existingIndex >= 0) {
          userCartItems[existingIndex].quantity += this.quantity;
        } else {
          userCartItems.push(cartItem);
        }

        cartItems = [...otherUserItems, ...userCartItems];
      } else {
        // 检查是否已存在相同SKU
        const existingIndex = cartItems.findIndex(item => item.id === cartItem.id);
        if (existingIndex >= 0) {
          cartItems[existingIndex].quantity += this.quantity;
        } else {
          cartItems.push(cartItem);
        }
      }

      // 保存购物车
      uni.setStorageSync('cartItems', cartItems);
      // 更新购物车数量显示
      this.loadCartCount();

      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      });

      this.closeSkuPopup();
    },

    // 立即购买
    buyNow() {
      if (this.isOutOfStock) {
        uni.showToast({
          title: '暂无库存',
          icon: 'none'
        });
        return;
      }

      if (!this.isSkuValid) {
        uni.showToast({
          title: '请选择有效规格',
          icon: 'none'
        });
        return;
      }

      // 获取用户信息
      const userInfo = this.userInfo

      // 创建订单数据
      // const orderData = {
      //   user_id: userInfo.id || null,
      //   items: [{
      //     product_id: this.product.id,
      //     sku_id: this.selectedSku.id,
      //     quantity: this.quantity,
      //     price: this.selectedSku.price
      //   }],
      //   total_amount: this.selectedSku.price * this.quantity
      // };

      // 跳转到确认订单页面
      uni.navigateTo({
        url: `/pages/cart/payment?sku_id=${this.selectedSku.id}&quantity=${this.quantity}`
      });

      this.closeSkuPopup();
    },

    // 跳转到购物车
    goToCart() {
      uni.navigateTo({
        url: '/pages/cart/cart'
      });
    }
  }
}
</script>

<style lang="scss">
.product-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;

  // 产品轮播图
  .product-swiper {
    background: #FFFFFF;

    .swiper {
      height: 600rpx;

      .swiper-image {
        width: 100%;
        height: 100%;
      }
    }
  }

  // 产品基本信息
  .product-info {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .price-section {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;

      .current-price {
        font-size: 48rpx;
        color: #ff4d4f;
        font-weight: bold;
        margin-right: 16rpx;
      }

      .original-price {
        font-size: 28rpx;
        color: #999999;
        text-decoration: line-through;
      }
    }

    .product-name {
      font-size: 32rpx;
      color: #333333;
      line-height: 1.4;
      margin-bottom: 16rpx;
      display: block;
    }

    .product-meta {
      display: flex;
      justify-content: space-between;

      .stock-info,
      .sales-info {
        font-size: 26rpx;
        color: #666666;
      }
    }
  }

  // 规格选择
  .spec-section {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .spec-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .spec-title {
        font-size: 28rpx;
        color: #333333;
      }

      .spec-selected {
        display: flex;
        align-items: center;

        .selected-text {
          font-size: 26rpx;
          color: #333333;
          margin-right: 8rpx;

          &.placeholder {
            color: #999999;
          }
        }

        .arrow-icon {
          width: 24rpx;
          height: 24rpx;
        }
      }
    }

    .stock-warning {
      margin-top: 16rpx;

      .warning-text {
        font-size: 24rpx;
        color: #ff4d4f;
      }
    }
  }

  // 产品详情
  .detail-section {
    background: #FFFFFF;
    padding: 32rpx;

    .section-title {
      margin-bottom: 24rpx;

      .title-text {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
      }
    }

    .detail-content {
      font-size: 28rpx;
      color: #666666;
      line-height: 1.6;
    }
  }

  // 底部操作栏
  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    //height: 100rpx;
    background: #FFFFFF;
    display: flex;
    align-items: center;
    padding: 24rpx;
    border-top: 1rpx solid #f0f0f0;
    z-index: 999;
    padding-bottom: 40rpx;
    .cart-btn {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 32rpx;

      .cart-icon {
        width: 48rpx;
        height: 48rpx;
        margin-bottom: 4rpx;
      }

      .cart-text {
        font-size: 20rpx;
        color: #666666;
      }

      .cart-badge {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        min-width: 32rpx;
        height: 32rpx;
        background: #ff4d4f;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20rpx;
        color: #FFFFFF;
        padding: 0 8rpx;
      }
    }

    .action-btns {
      flex: 1;
      display: flex;
      gap: 24rpx;

      .add-cart-btn,
      .buy-btn {
        flex: 1;

        &.disabled {
          background: #cccccc !important;
          color: #999999 !important;
          opacity: 0.6;
        }
      }

      .add-cart-btn {
        background: #FFC300;
        color: #FFFFFF;
        border: none;
      }
    }
  }

  // SKU选择弹窗
  .sku-popup {
    height: 100%;
    display: flex;
    flex-direction: column;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 32rpx;
      border-bottom: 1rpx solid #f0f0f0;

      .product-preview {
        display: flex;
        align-items: center;
        flex: 1;

        .preview-image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 16rpx;
          margin-right: 24rpx;
        }

        .preview-info {
          flex: 1;

          .preview-price {
            font-size: 36rpx;
            color: #ff4d4f;
            font-weight: bold;
            display: block;
            margin-bottom: 8rpx;
          }

          .preview-stock {
            font-size: 26rpx;
            color: #666666;
          }
        }
      }

      .popup-close {
        font-size: 48rpx;
        color: #999999;
        line-height: 1;
        padding: 8rpx;
      }
    }

    .popup-content {
      flex: 1;
      padding: 32rpx;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      .sku-section-list {
        flex: 1;
        overflow: hidden;
      }
      .sku-section {
        margin-bottom: 32rpx;

        .spec-name {
          font-size: 28rpx;
          color: #333333;
          margin-bottom: 16rpx;
          display: block;
        }

        .spec-options {
          display: flex;
          flex-wrap: wrap;
          gap: 16rpx;

          .spec-option {
            color: #fff;
            padding: 8rpx 24rpx;
            background: #f8f8f8;
            border-radius: 12rpx;
            border: 2rpx solid transparent;

            &.active {
              background: #FFC300;
              .option-text {
                color:#333;
              }
            }

            .option-text {
              font-size: 26rpx;
              color: #666;
            }
          }
        }
      }

      .quantity-section {
        flex-shrink: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .quantity-label {
          font-size: 28rpx;
          color: #333333;
        }

        .quantity-control {
          display: flex;
          align-items: center;

          .quantity-btn {
            width: 64rpx;
            height: 64rpx;
            background: #f8f8f8;
            border-radius: 8rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32rpx;
            color: #333333;
          }

          .quantity-input {
            width: 120rpx;
            height: 64rpx;
            text-align: center;
            margin: 0 16rpx;
            background: #f8f8f8;
            border-radius: 8rpx;
            font-size: 28rpx;
          }
        }
      }
    }

    .popup-footer {
      padding: 32rpx;
      border-top: 1rpx solid #f0f0f0;
      display: flex;
      gap: 24rpx;

      .add-cart-action-btn,
      .buy-action-btn {
        flex: 1;

        &.disabled {
          background: #cccccc !important;
          color: #999999 !important;
          opacity: 0.6;
        }
      }

      .add-cart-action-btn {
        background: #FFC300;
        color: #FFFFFF;
        border: none;
      }
    }
  }
}
</style>
